from .models import *
from utils.check_permission import check_custom_perms

# 此为上下文处理器，给上下文信息中的 extend的html页面传入参数
# 主要目的是，给base上的字段传入站内信等数据

# 设置好之后，需要在setting上引用此函数template下的contents_processor
# 上下文处理器（给header和footer传入参数）
#'home.context_processors.getBasicInfo',

def getMsg(request):
    # 公共信息
    uid = request.user.id
    # 获取用户发出的未读消息
    msg_counts = Msg.objects.filter(receiver_id=uid).filter(read_status=False).exclude(sender_id=1).all().count()

    # 获取系统发出的未读消息
    sys_msg_counts = Msg.objects.filter(receiver_id=uid).filter(read_status=False).filter(sender_id=1).all().count()
    # 获取用户未读消息（来自用户）
    msg_from_user = []
    _user_data = Msg.objects.filter(receiver_id=uid).filter(read_status=False).exclude(sender_id=1).all()
    for j in _user_data:
        x = {}
        x['mid'] = j.id
        x['sender_head_pic'] = j.sender.head_pic
        x['contents'] = j.contents
        x['sender_username'] = j.sender.username
        x['send_time'] = j.send_time
        x['subject'] = j.subject
        msg_from_user.append(x)

    # 获取用户未读消息（系统发送的）
    # 获取用户未读消息（来自用户）
    msg_from_sys = []
    _sys_data = Msg.objects.filter(receiver_id=uid).filter(read_status=False).filter(sender_id=1).all()
    for j in _sys_data:
        x = {}
        x['mid'] = j.id
        x['sender_head_pic'] = j.sender.head_pic
        x['contents'] = j.contents
        x['sender_username'] = j.sender.username
        x['send_time'] = j.send_time
        x['subject'] = j.subject
        msg_from_sys.append(x)
    # 以下为动态菜单函数
    # 获取菜单信息
    menu_data = []
    menu_1 = Menu.objects.filter(pid=0, show=True).order_by("order_num")
    if not menu_1:
        # 没有菜单，添加默认菜单
        new_1 = Menu(id=1, name="系统面板", url="#", icon="""<i class="nav-icon fas fa-user"></i>""",
                     pid=0, order_num=999)
        new_1.save()
        new_2 = Menu(id=2, name="创建用户", url="/login/user/add/", icon="""<i class="far fa-circle nav-icon"></i>""",
                     pid=1, order_num=1000)
        new_2.save()
        new_3 = Menu(id=3, name="用户列表", url="/login/user/list/", icon="""<i class="far fa-circle nav-icon"></i>""",
                     pid=1, order_num=1000)
        new_3.save()
        new_4 = Menu(id=4, name="部门设置", url="/login/department/", icon="""<i class="far fa-circle nav-icon"></i>""",
                     pid=1, order_num=1000)
        new_4.save()
        new_5 = Menu(id=5, name="职位管里", url="/login/position/", icon="""<i class="far fa-circle nav-icon"></i>""",
                     pid=1, order_num=1000)
        new_5.save()
        new_6 = Menu(id=6, name="菜单管理", url="/login/menu/", icon="""<i class="far fa-circle nav-icon"></i>""",
                     pid=1, order_num=1000)
        new_6.save()
        new_7 = Menu(id=7, name="角色管理", url="/login/role/", icon="""<i class="far fa-circle nav-icon"></i>""",
                     pid=1, order_num=1000)
        new_7.save()
        new_8 = Menu(id=8, name="操作日志", url="/login/logs/", icon="""<i class="far fa-circle nav-icon"></i>""",
                     pid=1, order_num=1000)
        new_8.save()
        # 保存初始数据完成，重新生成菜单
        menu_1 = Menu.objects.filter(pid=0, show=True).order_by("order_num")
    # 先整合一级菜单
    for m in menu_1:
        checked_1 = False   # 一级菜单标记
        checked_2 = False   # 二级菜单标记
        checked_3 = False   # 三级菜单标记
        item = {}
        item["name"] = m.name
        item["icon"] = m.icon
        item["url"] = m.url
        # 获取二级菜单
        data_2 = Menu.objects.filter(pid=m.id, show=True).all().order_by("order_num")
        if data_2:
            sub_2 = []
            for m2 in data_2:
                item2 = {"name": m2.name, "icon": m2.icon, "url": m2.url}
                if check_custom_perms(m2.id, uid, 'read'):
                    # 有查看权限，才整合菜单
                    sub_2.append(item2)
                    checked_1 = True
                    checked_2 = True
                # 获取三级菜单
                data_3 = Menu.objects.filter(pid=m2.id, show=True).all().order_by("order_num")
                if data_3:
                    sub_3 = []
                    for m3 in data_3:
                        item3 = {"name": m3.name, "icon": m3.icon, "url": m3.url}
                        if check_custom_perms(m3.id, uid, 'read'):
                            # 有查看权限，才整合菜单
                            sub_3.append(item3)
                            checked_1 = True   # 一级菜单标记，如果子菜单有权限，而父菜单没有权限，则需展示菜单
                            checked_2 = True   # 一级菜单标记，如果子菜单有权限，而父菜单没有权限，则需展示菜单
                            checked_3 = True   # 一级菜单标记，如果子菜单有权限，而父菜单没有权限，则需展示菜单
                    if checked_3:
                        # 三级菜单有权限，才添加
                        item2["sub"] = sub_3
                else:
                    item2["sub"] = ""
            if checked_2:
                # 二级菜单有权限才添加
                item["sub"] = sub_2
        else:
            item["sub"] = ""
        # 一级菜单有权限才添加
        if checked_1:
            menu_data.append(item)
    # 返回的必须是字典
    return {
        'msg_not_read': msg_counts,
        'sys_msg_not_read': sys_msg_counts,
        'msg_from_user': msg_from_user,
        'msg_from_sys': msg_from_sys,
        'menu_data': menu_data,
    }
